package com.example.gaodemapdemo;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.Circle;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;

import java.io.File;

public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener,AMap.InfoWindowAdapter{

    private AMap aMap;
    private MapView mMapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;



    private TextView mLocationErrText;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    private boolean mFirstFix = false;
    private Marker mLocMarker;
    private Circle mCircle;
    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private PopupWindow mPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMapView = (MapView) findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        init();

    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            setUpMap();
        }
    }


    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false


        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//只定位一次。
//        myLocationStyle.interval(5000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒

        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.location_marker));// 设置小蓝点的图标

        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色

        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色

         myLocationStyle.anchor(0.5f,0.5f);//设置小蓝点的锚点 (已小蓝点为中心)

        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细

        aMap.setMyLocationStyle(myLocationStyle);

        // aMap.setMyLocationType();
        //  }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();

            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }


    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        Log.d("map", amapLocation.getAddress());

/*        //23.6872893784,113.0465698242  // 假数据
        double latitude = 23.6872893784;
        double longitude = 113.0465698242;
        amapLocation.setLatitude(latitude);
        amapLocation.setLongitude(longitude);*/


        if (mListener != null&&amapLocation != null) {
            if (amapLocation != null
                    &&amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }


        LatLng latLng = new LatLng(39.906901,116.397972);
        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("北京").snippet("DefaultMarker"));

        aMap.setOnMarkerClickListener(mOnMarkerClickListener);
        aMap.setInfoWindowAdapter(this);

/*
        mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(),amapLocation.getLongitude())));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(18));*/
    }



    private AMap.OnMarkerClickListener mOnMarkerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            Toast.makeText(MainActivity.this, "marker", Toast.LENGTH_SHORT).show();
            return false;
        }
    };

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }


   private View infoWindow = null;

    @Override
    public View getInfoContents(Marker marker) {
        if(infoWindow == null) {
            infoWindow = LayoutInflater.from(this).inflate(
                    R.layout.custom_info_window, null);
        }
        render(marker, infoWindow);
        return infoWindow;
//加载custom_info_window.xml布局文件作为InfoWindow的样式
//该布局可在官方Demo布局文件夹下找到
    }

    private void render(final Marker marker, View infoWindow) {
        Button btn = (Button) infoWindow.findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转地图
                LatLng position = marker.getPosition();
                showPopupWindow(position);
            }
        });
    }


    //移动APP调起Android高德地图方式
    private void startGaoDeMap(LatLng latitude) {
        Intent intent = new Intent("android.intent.action.VIEW",
                android.net.Uri.parse("androidamap://navi?sourceApplication=amap&lat=" + latitude.latitude + "&lon=" + latitude.longitude + "&dev=1&style=0"));
        intent.setPackage("com.autonavi.minimap");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (isInstallByread("com.autonavi.minimap")) {
            startActivity(intent);
        } else {
            Toast.makeText(this, "没有安装高德地图客户端", Toast.LENGTH_SHORT).show();
        }
    }



    //移动APP调起Android百度地图方式
    public void startBaiduMap(LatLng latitude) {
        Intent intent = null;
        try {
            intent = Intent.getIntent("intent://map/direction?destination=latlng:" + latitude.latitude  + "," + latitude.longitude + "|name:&origin=" + "我的位置" + "&mode=driving?ion=" + "我的位置" + "&referer=Autohome|GasStation#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isInstallByread("com.baidu.BaiduMap")) {
            startActivity(intent); // 启动调用
        } else {
            Toast.makeText(this, "没有安装百度地图客户端", Toast.LENGTH_SHORT).show();
        }
    }


    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName)
                .exists();
    }



    private void showPopupWindow(LatLng latLng) {
        //设置contentView
        View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popup_view, null);
        mPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        //设置各个控件的点击响应
        Button tv1 = (Button)contentView.findViewById(R.id.btn_baidu_map);
        Button tv2 = (Button)contentView.findViewById(R.id.btn_gaode_map);

        MyonClicklistenner myonClicklistenner = new MyonClicklistenner(latLng);
        tv1.setOnClickListener(myonClicklistenner);
        tv2.setOnClickListener(myonClicklistenner);

        //显示PopupWindow
        View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
        //进入退出的动画
        mPopWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

    }

    class MyonClicklistenner implements View.OnClickListener{
        private LatLng latLng;

        public MyonClicklistenner(LatLng latLng) {
            this.latLng = latLng;
        }
        @Override
        public void onClick(View v) {

            switch (v.getId()){
                case R.id.btn_baidu_map:
                    startBaiduMap(latLng);
                    break;
                case R.id.btn_gaode_map:
                    startGaoDeMap(latLng);
                    break;
            }
        }
    }


}
